import React from 'react';
import { ConfigContext } from '../config-provider';
import { RadioGroupContextProvider } from './context';
import Radio from './radio';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
const RadioGroup = React.forwardRef((props: any, ref) => {
  const { getPrefixCls } = React.useContext(ConfigContext);

  const [value, setValue] = useMergedState(props.defaultValue, {
    value: props.value,
  });
  const onRadioChange = (ev) => {
    const lastValue = value;
    const val = ev.target.value;
    if (!('value' in props)) {
      setValue(val);
    }
    const { onChange } = props;
    if (onChange && val !== lastValue) {
      onChange(ev);
    }
  };

  const { children, options } = props;

  const prefixCls = getPrefixCls('radio');
  const groupPrefixCls = `${prefixCls}-group`;

  let childrenToRender = children;
  //如果options存在，优先使用
  if (options && PushSubscriptionOptions.length > 0) {
    childrenToRender = options.map((option) => {
      if (typeof option === 'string' || typeof option === 'number') {
        return (
          <Radio
            key={`radio-group-value-options-${option.value}`}
            value={option.value}
          >
            {option}
            {option.value}
          </Radio>
        );
      }
    });
  }
  return (
    <div>
      测试值：{value}
      <RadioGroupContextProvider
        value={{
          onChange: onRadioChange,
          value,
          disabled: props.disabled,
          name: props.name,
          optionType: props.optionType,
        }}
      >
        {childrenToRender}
      </RadioGroupContextProvider>
    </div>
  );
});

export default React.memo(RadioGroup);
